package buildrobot_info

import (
	"go_server/game_server/api/service/build"
	"go_server/game_server/protocol/pb"
	"go_server/zinx/ziface"
	"go_server/zinx/zlog"
)

func (s *Buildrobot_info_service) S2C_DelBuildRobotLvUp(conn ziface.IConnection, roleid int64, msg *pb.DelRobot2BuildLvUpC2S) pb.ErrorCodeManager {
	robot := s.LoadByRoleId(roleid)
	isAnyBuildUpgradeSuc := false
	if robot != nil {
		build_info_id := build.CombinBuildKey(roleid, msg.Buildmapid, msg.Buildcfgid, msg.Buildserid)
		if build.CheckdBuildConsumeStatus(build_info_id) {
			if build, ok := robot.BuildData[build_info_id]; ok {
				isRemove := false
				if msg.GetDelallrobot() {
					isRemove = build.RemoveAllRobot(robot.GetRobotBySerid)
				} else {
					_, isRemove = build.RemoveRobot(msg.Robotserids, robot.GetRobotBySerid)
				}
				if isRemove {
					if build.CalculateUpgradeTime(robot.TransVolume, robot.GetRobotBySerid, false) {
						isAnyBuildUpgradeSuc = true
						delete(robot.BuildData, build.Build_info_id)
					}
				} else {
					build.CheckUpgradeState(robot.GetRobotBySerid, false)
				}
				msgS2C := &pb.DelRobot2BuildLvUpS2C{}
				msgS2C.IdleRobots = robot.Pb_GetIdleRobot()
				msgS2C.Builds = make([]*pb.BuildRobotLvUpData, 1)
				msgS2C.Builds[0] = build.ToPb_BuildRobotLvUpData(robot.GetRobotBySerid)
				if msgS2C != nil {
					zlog.Debugf("ProtocolManager_DelBuildRobotLvUp %v", msgS2C)
					defer func() {
						conn.SendBuffPBMsg(uint32(pb.ProtocolManager_DelBuildRobotLvUp), msgS2C)
					}()
				}
				defer func() {
					robot.Save_AllData()
				}()
			}
			if isAnyBuildUpgradeSuc {
				Buildrobot_info_serviceObj.S2C_BuildRobotUpgradeSuc(conn, robot)
			}
		} else {
			return pb.ErrorCodeManager_BUILDROBOTINFO_NOT_UP2BUILDING
		}
	}

	return pb.ErrorCodeManager_SUCCESS
}
